package org.terramagnet.mvcframework.friendly;

import java.util.Locale;
import javax.annotation.Resource;
import org.springframework.context.MessageSource;
import org.terramagnet.mvcframework.tools.SpringMvcUtils;

/**
 * 使用SpringMVC的国际化资源来生成友好化信息.
 *
 * @author lip
 */
public final class I18nFriendly implements Friendly {

    public static final I18nFriendly DEFAULT = new I18nFriendly(500, "error.default");
    public static final I18nFriendly ILLEGAL_ARGUMENT_VALUE = new I18nFriendly(400, "error.argument.value.illegal");
    public static final I18nFriendly ILLEGAL_ARGUMENT = new I18nFriendly(400, "error.argument.illegal");

    private final int code;
    private final String template;
    @Resource
    private MessageSource messageSource;

    public I18nFriendly(int code, String template) {
        this.code = code;
        this.template = template;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getTemplate() {
        return template;
    }

    @Override
    public String toFriendly(Locale locale, Object... params) {
        if (messageSource == null) {
            messageSource = SpringMvcUtils.currentApplicationContext().getBean(MessageSource.class);
        }
        return messageSource.getMessage(template, params, locale);
    }

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

}
